<template>
  <div>
    <el-form :model="msg.data" :rules="rules" ref="form" label-position="left" label-width="30%" class="ml30">
      <el-form-item label="标签名称：" prop="value">
        <el-input class="width80" v-model="msg.data.value"></el-input>
      </el-form-item>
      <el-form-item label="颜色：" prop="color">
        <el-select class="width80" v-model="msg.data.color" placeholder="请选择">
          <el-option label="primary" value="primary">
            <span style="color:#409EFF">primary</span>
          </el-option>
          <el-option label="success" value="success">
            <span style="color:#67C23A">success</span>
          </el-option>
          <el-option label="info" value="info">
            <span style="color:#909399">info</span>
          </el-option>
          <el-option label="warning" value="warning">
            <span style="color:#E6A23C">warning</span>
          </el-option>
          <el-option label="danger" value="danger">
            <span style="color:#F56C6C">danger</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="标签预览：">
        <el-tag :type="msg.data.color">{{msg.data.value}}</el-tag>
      </el-form-item>
    </el-form>
    <div class="footer">
      <el-button class="el-button--blue" type="primary" @click="submitLabelChange">保 存</el-button>
      <el-button @click="msg.visible=false">关 闭</el-button>
    </div>
  </div>
</template>

<script>
import { awaitCheckLabel, SubmitLabelChange } from '../../../api/form'
export default {
  name: 'label-change',
  model: {
    prop: 'msg',
    event: 'cc'
  },
  props: {
    msg: {}
  },
  data () {
    let validateLabel = (rule, value, callback) => {
      if (this.msg.data.value !== '' && this.msg.data.color !== '') {
        let res = awaitCheckLabel(this.msg.data.value, this.msg.data.color, this.msg.data.id)
        if (res.status === 200) {
          if (!res.responseJSON.result) {
            callback(new Error(res.responseJSON.msg))
          } else {
            callback()
          }
        }
      }
      callback()
    }
    return {
      rules: {
        labelName: [
          { required: true, message: '标签名称不能为空', trigger: 'change' },
          { validator: validateLabel, trigger: 'blur' }
        ],
        color: [
          { required: true, message: '请选择颜色', trigger: 'change' },
          { validator: validateLabel, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    submitLabelChange () {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          SubmitLabelChange(this.msg.data).then((res) => {
            this.msg.visible = false
            this.$store.dispatch('SetFlash')
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style scoped>
  .width80 {
    width: 80%;
  }
  .footer {
    display: flex;
    justify-content: flex-end;
  }
</style>
